#!/bin/bash

# File locations
BackgroundsPath=/media/hdb5/backgrounds
BackgroundPath=/tmp/background.jpg
TempLog=/tmp/backgrounds.log

# Create a temporary logfile of all matches
find $BackgroundsPath -iregex ".*.jpg" > $TempLog

# Choose a random line number (any number from 1 to the length of the file)
LowerBound=1
RandomMax=32767
UpperBound=$(cat $TempLog | wc -l)
RandomLeft=$(( $LowerBound + ($UpperBound * $RANDOM) / ($RandomMax + 1) ))
RandomRight=$(( $LowerBound + ($UpperBound * $RANDOM) / ($RandomMax + 1) ))

# Use sed to grab the random line
Left=$(sed -n "$RandomLeft{p;q;}" "$TempLog")
Right=$(sed -n "$RandomRight{p;q;}" "$TempLog")

convert $Left $Right +append $BackgroundPath

fbsetbg $BackgroundPath

